package com.example.happiness.service.admin.Impl;

import com.example.happiness.constant.Message;
import com.example.happiness.mapper.EmployeeMapper;
import com.example.happiness.mapper.OrderMapper;
import com.example.happiness.pojo.Employee;
import com.example.happiness.pojo.adminvo.AdminMangeEmployVO;
import com.example.happiness.pojo.adminvo.AdminOrderVO;
import com.example.happiness.result.Result;
import com.example.happiness.service.admin.AdminEmployService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.Objects;

@Service
public class AdminEmployServiceImpl implements AdminEmployService {

    @Autowired
    EmployeeMapper employeeMapper;
    @Autowired
    OrderMapper orderMapper;

    public List<Employee> getAllEmploy() {
        return employeeMapper.getAllEmploy(Message.ONE);
    }

    @Transactional
    public List<AdminMangeEmployVO> getEmployAndOrder() {
        List<AdminMangeEmployVO> employAndOrder = employeeMapper.getEmploy();
        for(AdminMangeEmployVO adminMangeEmployVO : employAndOrder){
            List<AdminOrderVO> orders = orderMapper.getOrder(adminMangeEmployVO.getEmployeeid());
            adminMangeEmployVO.setOrderList(orders);
        }
        return employAndOrder;
    }

    public Result addEmployee(Employee employee) {
        Employee employee1 = employeeMapper.selectByPrimaryKey(employee.getEmployeeid());
        if(employee1 != null){
            return Result.error("该员工已存在");
        }
        employee.setPassword(DigestUtils.md5DigestAsHex(employee.getPassword().getBytes()));
        employeeMapper.insert(employee);
        return Result.success();
    }

    public void upEmployee(Employee employee) {
        if(employee.getPassword() != null && !Objects.equals(employee.getPassword(), "")){
            employee.setPassword(DigestUtils.md5DigestAsHex(employee.getPassword().getBytes()));
        }else {
            Employee employee1 = employeeMapper.selectByPrimaryKey(employee.getEmployeeid());
            employee.setPassword(employee1.getPassword());
        }
        employeeMapper.updateByPrimaryKeySelective(employee);
    }

    public void delEmployee(String employid) {
        employeeMapper.deleteByPrimaryKey(employid);
    }
}
